{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-08-18T14:57:18.374459Z",
     "start_time": "2025-08-18T14:57:17.395463Z"
    }
   },
   "source": [
    "# 创建模型实例\n",
    "from langchain_openai import ChatOpenAI\n",
    "import os\n",
    "chat_model = ChatOpenAI(\n",
    "    # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key=\"sk-xxx\",\n",
    "    api_key=os.getenv(\"DASH_SCOPE_API_KEY\"), # 如何获取API Key：https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key\n",
    "    base_url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n",
    "    model=\"qwen-plus\",\n",
    "    temperature=0.8,\n",
    "    max_tokens=60,\n",
    ")\n",
    "\n",
    "from langchain.output_parsers import PydanticOutputParser\n",
    "from pydantic import BaseModel, Field\n",
    "from typing import List\n",
    "\n",
    "# 使用Pydantic创建一个数据格式，表示花\n",
    "class Flower(BaseModel):\n",
    "    name: str = Field(description=\"name of a flower\")\n",
    "    colors: List[str] = Field(description=\"the colors of this flower\")\n",
    "# 定义一个用于获取某种花的颜色列表的查询\n",
    "flower_query = \"Generate the charaters for a random flower.\"\n",
    "\n",
    "# 定义一个格式不正确的输出\n",
    "misformatted = \"{'name': '康乃馨', 'colors': ['粉红色','白色','红色','紫色','黄色']}\"\n",
    "\n",
    "# 创建一个用于解析输出的Pydantic解析器，此处希望解析为Flower格式\n",
    "parser = PydanticOutputParser(pydantic_object=Flower)\n",
    "\n",
    "# 使用Pydantic解析器解析不正确的输出\n",
    "# parser.parse(misformatted) # 这行代码会出错\n",
    "\n",
    "# 从langchain库导入所需的模块\n",
    "from langchain.output_parsers import OutputFixingParser\n",
    "\n",
    "# 使用OutputFixingParser创建一个新的解析器，该解析器能够纠正格式不正确的输出\n",
    "new_parser = OutputFixingParser.from_llm(parser=parser, llm=chat_model)\n",
    "\n",
    "# 使用新的解析器解析不正确的输出\n",
    "result = new_parser.parse(misformatted) # 错误被自动修正\n",
    "print(result) # 打印解析后的输出结果"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "name='康乃馨' colors=['粉红色', '白色', '红色', '紫色', '黄色']\n"
     ]
    }
   ],
   "execution_count": 2
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
